<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <div id="box"></div>
        <h4>已经添加的水果：</h4>
        <div
            style="width: 200px; height: 200px; border: 1px solid red"
            id="selectBox"
        ></div>
        <button id="btn">清除所有已添加的水果</button>
        <script>
            let arr = [
                { id: 1, value: "苹果" },
                { id: 2, value: "香蕉" },
                { id: 3, value: "葡萄" },
            ];
            let box = document.querySelector("#box");
            let selectBox = document.querySelector("#selectBox");
            let btn = document.querySelector("#btn");
            function fruit(text) {
                //定义值

                let div1 = document.createElement("div");
                let span1 = document.createElement("span");
                let span2 = document.createElement("span");
                let txt1 = document.createTextNode(text);
                let txt2 = document.createTextNode("+");

                //添加的水果
                box.appendChild(div1);
                div1.appendChild(span1);
                div1.appendChild(span2);
                span1.appendChild(txt1);
                span2.appendChild(txt2);
                //添加方法
                // let span3 = document.createElement("span");
                // let txt3 = document.createTextNode(text);
                // 放外面无法重复，为什么？
                span2.onclick = function () {
                    let span3 = document.createElement("span");
                    let txt3 = document.createTextNode(text);
                    selectBox.appendChild(span3);
                    span3.appendChild(txt3);
                    span3.onclick = function () {
                        selectBox.removeChild(span3);
                    };
                };
            }
            for (let i = 0; i < arr.length; i++) {
                fruit(arr[i].value);
            }
            btn.onclick = function () {
                selectBox.innerHTML = "";
            };
        </script>
    </body>
</html>
